import React from 'react';
import {I18n} from '../../reducers/intl';
import {StyleSheet, Text, View, Dimensions, Platform} from 'react-native';
import {getRealSize, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import SheetHead from '../../components/items/sheet-head';
import BottomSheet from '@gorhom/bottom-sheet';
import {GooglePlacesAutocomplete} from 'react-native-google-places-autocomplete';
import Config from '../../../config.json';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
import {bindActionCreators} from 'redux';
import * as profileActionCreator from '../../actions/profile-actions';
import * as registerActionCreator from '../../actions/register-action';
import {connect} from 'react-redux';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import HttpClient from '../../commons/http-client';
import axios from 'axios';
import _ from 'lodash';
import Toast from '../../components/toast';
const {width, height} = Dimensions.get('window');

const ASPECT_RATIO = width / height;

const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

class LocationScreen extends React.PureComponent {
  static navigationOptions = ({navigation}) => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.location'),
    headerLeft: () => (
      <Touchable onPress={() => navigation.goBack()}>
        <View style={[ThemeStyles.Layout.base.padding]}>
          <Text style={[ThemeStyles.Front.base, {width: 50, height: 20}]}>
            {I18n.t('button.cancel')}
          </Text>
        </View>
      </Touchable>
    ),
    headerRight: () => (
      <Touchable onPress={() => navigation.getParam('onSave')()}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text style={[ThemeStyles.Front.base]}>{I18n.t('button.apply')}</Text>
        </View>
      </Touchable>
    ),
  });
  state = {
    sheetIndex: -1,
    location: null,
  };

  componentDidMount() {
    const {appState, navigation} = this.props;
    // console.log(appState);
    this.setState({location: appState.location});
    navigation.setParams({onSave: this.onSave});
  }

  onSave = () => {
    const {profileActions, registerActions, navigation} = this.props;
    const isRegister = navigation.getParam('register');
    try {
      profileActions.updateAddress(this.state.location);
      if (isRegister) {
        registerActions.updateAddress(this.state.location);
      }
      navigation.goBack();
    } catch (e) {
      Toast.show(e.message);
    }
  };

  async onRegionChange(region) {
    const {intl} = this.props;
    this.setState({center: region});
    const payload = {
      key: Config.googleKey,
      latlng: `${region.latitude},${region.longitude}`,
      sensor: false,
      language: intl,
    };
    const params = HttpClient.encodeParams(payload);
    const url = 'https://maps.googleapis.com/maps/api/geocode/json?' + params;
    try {
      const result = await axios.get(url);
      // console.log(url, result);
      const location = {
        latitude: region.latitude,
        longitude: region.longitude,
        address: _.get(result, 'data.results[0].formatted_address', ''),
        country: _.get(
          result,
          'data.results[0].address_components',
          [],
        ).find(item => item.types.includes('country')).long_name,
      };
      this.setState({location});
    } catch (e) {
      Toast.show(e.message);
    }
  }

  render() {
    const {intl} = this.props;
    const {location} = this.state;
    const mapStyle = [];
    return (
      <View style={{flex: 1}}>
        {location && (
          <MapView
            customMapStyle={mapStyle}
            provider={PROVIDER_GOOGLE}
            ref={ref => {
              this.map = ref;
            }}
            style={Styles.mapBox}
            onPress={() => this.BottomSheet.snapTo(1)}
            // mapType={Platform.OS == 'android' ? 'none' : 'standard'}
            initialRegion={{
              latitude: location.latitude,
              longitude: location.longitude,
              latitudeDelta: LATITUDE_DELTA,
              longitudeDelta: LONGITUDE_DELTA,
            }}
            // onRegionChange={region => this.onRegionChange(region)}
            // showsUserLocation
            onRegionChangeComplete={region => this.onRegionChange(region)}>
            <Marker
              // draggable
              coordinate={location}
              // title={appState.location.address}
              // onDragEnd={e => this.setState({center: e.nativeEvent.coordinate})}
              onPress={e => {
                if (e.nativeEvent.action === 'marker-press') {
                  // console.log(e);
                  this.BottomSheet.snapTo(1);
                }
              }}
            />
          </MapView>
        )}
        {location && (
          <View style={[Styles.bubble, Styles.latlng]}>
            <Text style={Styles.centeredText}>{location.address}</Text>
          </View>
        )}
        <BottomSheet
          ref={ref => {
            this.BottomSheet = ref;
          }}
          style={Styles.sheetContainer}
          index={this.state.sheetIndex}
          handleComponent={() => (
            <SheetHead onClose={() => this.BottomSheet.close()} />
          )}
          snapPoints={[-1, '60%']}>
          <GooglePlacesAutocomplete
            placeholder="Search"
            // autoFocus
            fetchDetails
            onPress={(data, details = null) => {
              // 'details' is provided when fetchDetails = true
              // console.log(JSON.stringify(data), JSON.stringify(details));
              const latitude = _.get(details, 'geometry.location.lat', 0);
              const longitude = _.get(details, 'geometry.location.lng', 0);
              const address = details.formatted_address;
              const addressResult = _.get(details, 'address_components', []);
              const country = addressResult.find(item =>
                item.types.includes('country'),
              );
              const location = {
                latitude,
                longitude,
                address,
                country: country ? country.name : '',
              };
              // console.log('location', location);
              this.setState({location});
              this.map.animateToRegion(
                {
                  latitude: location.latitude,
                  longitude: location.longitude,
                  latitudeDelta: LATITUDE_DELTA,
                  longitudeDelta: LONGITUDE_DELTA,
                },
                500,
              );
              this.BottomSheet.close();
              this.BottomSheet.snapTo(0);
            }}
            query={{
              key: Config.googleKey,
              language: intl,
              types: 'geocode',
            }}
          />
        </BottomSheet>
      </View>
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  intl: state.intl,
  user: state.user,
});

const mapDispatchToProps = dispatch => ({
  profileActions: bindActionCreators(profileActionCreator, dispatch),
  registerActions: bindActionCreators(registerActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(LocationScreen));

const Styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ccc',
  },
  mapBox: {
    ...StyleSheet.absoluteFillObject,
    // width: Dimensions.get('window').width,
    // height: Dimensions.get('window').height,
  },
  sheetContainer: {
    borderTopColor: ThemeStyles.Color.line.color,
    borderTopWidth: StyleSheet.hairlineWidth,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 12,
    },
    shadowOpacity: 0.58,
    shadowRadius: 16.0,

    elevation: 24,
  },
  bubble: {
    backgroundColor: 'rgba(255,255,255,0.7)',
    paddingHorizontal: 18,
    paddingVertical: 12,
    borderRadius: 20,
  },
  latlng: {
    alignItems: 'stretch',
  },
  centeredText: {textAlign: 'center'},
  plainView: {},
});
